<?php
/**
 * Created by PhpStorm.
 * User: xudongsheng
 * Date: 2017/9/18
 * Time: 下午1:59
 */

namespace app\admin\controller;
use app\admin\model\FriendshipLink as linkModel;
use think\Request;

class FriendshipLink extends Common
{
    protected $rule =   [
            'createEdit'    =>  [
                'site_name|网站名称'      =>  'require|max:18|min:1|token',
                'url|地址'               =>  'require|max:200',
            ],
    ];

    /** 友链 列表
     * @return mixed
     */
    public function lists(){
       $links =  linkModel::order('sort','desc')->paginate();
       $this->assign('links',$links);
       return $this->fetch();
    }

    /** 创建 模板页
     * @param Request $request
     * @return mixed
     */
    public function create(Request $request){
        $request->isPost() AND $this->createSave();
        return $this->fetch();
    }

    /**
     * 创建 之 保存
     */
    private function createSave(){
        (($checkMsg =  $this->validate(input('post.'),$this->rule['createEdit'])) !== true) AND $this->error($checkMsg);
        if (linkModel::create(input('post.'),true)){
            $this->success('添加成功！',url('friendship_link/lists'));
        }
        $this->error('添加失败！');
    }

    /** 更新 之 编辑 模板
     * @param Request $request
     * @param $link_id
     * @return mixed
     */
    public function edit(Request $request,$link_id){
        ($link =  linkModel::get($link_id)) OR $this->error('不存在此友情链接,无法编辑！');
        $request->isPost() AND $this->updateSave($link);
        $this->assign('link',$link);
        return $this->fetch();
    }

    /** 更新 之 编辑 保存数据
     * @param $link
     */
    private function updateSave($link){
        (($checkMsg =  $this->validate(input('post.'),$this->rule['createEdit'])) !== true) AND $this->error($checkMsg);
        if (linkModel::update(input('post.'),['link_id'=>$link->link_id],true)){
            $this->success('更新成功！',url('admin/friendship_link/lists'));
        }
            $this->error('更新失败！');
    }

    /** 排序
     * @param $sort
     */
    public function sort($sort){
        (!is_array($sort) OR empty($sort)) AND $this->error('没有要排序项！');
        foreach ($sort as $k=>$v){
            linkModel::update([
                'link_id'  =>  (int)$k,
                'sort'       =>  (int)$v
            ]);
        }
        $this->success('已排序~');
    }

    public function del($link_id){
        if (linkModel::destroy($link_id)){
            $this->success('删除成功！',url('admin/friendship_link/lists'));
        }
        $this->error('删除失败！');
    }








}